#include "vertex_types.fxh"
#include "Samplers.fxh"
#include "globals.fxh"


TNORMAL_TEXTURED_VERTEX_PS RenderVS(TNORMAL_TEXTURED_VERTEX_VS IN)
{
 
    TNORMAL_TEXTURED_VERTEX_PS OUT = (TNORMAL_TEXTURED_VERTEX_PS )0;
    OUT.HPosition=mul(float4(IN.Position,1.0),g_WorldViewProjectionMatrix);
    OUT.UV=IN.UV;
    OUT.WorldNormal=mul(IN.Normal,(float3x3) g_WorldMatrix);
    OUT.WorldPosition=mul(float4(IN.Position,1.0), g_WorldMatrix);
    return OUT;
}

float4 RenderPS(TNORMAL_TEXTURED_VERTEX_PS IN) : COLOR
{
	//return float4(g_CameraPosition, 1.0);
	// m_CameraPosition

	float3 l_LightDir = IN.WorldPosition-g_LightsPosition[0];
	float3 l_NormalizedLightDir = l_LightDir/length(l_LightDir);
	float l_DistAtt = 1 - saturate((length(l_LightDir) - g_LightsStartRangeAttenuation[0])/(g_LightsEndRangeAttenuation[0] - g_LightsStartRangeAttenuation[0]));
	
	
	// TODO
	float g_SpecularPower = 200;
	float g_SpecularMaterialFactor = 0.8;
	float g_DiffuseMaterialFactor = 0.8;
	float4 g_AmbientLight = {0.2, 0.2, 0.2, 1.0};
	
	//Specular
    float3 Nn=normalize(IN.WorldNormal);
    float3 Hn=normalize(normalize(g_CameraPosition-IN.WorldPosition)-l_NormalizedLightDir);
    float l_SpecularContrib=pow(saturate(dot(Hn, Nn)), g_SpecularPower);
    float3 l_SpecularLighting=l_SpecularContrib*g_LightsColor[0]*l_DistAtt*g_SpecularMaterialFactor;
	//return float4(l_SpecularLighting, 1.0);

	
	//Diffuse
	
    float l_DiffuseContrib=saturate(dot(Nn, -l_NormalizedLightDir));
	
	//return float4(l_DiffuseContrib,l_DiffuseContrib,l_DiffuseContrib,1.0);
	float3 l_DiffuseLightColor = g_LightsColor[0]*l_DiffuseContrib*l_DistAtt*g_DiffuseMaterialFactor;
	//return float4(l_DiffuseLightColor, 1.0);
	//return float4(l_DiffuseContrib,l_DiffuseContrib,l_DiffuseContrib,1.0);
    float3 l_TotalColor=g_AmbientLight.xyz+l_DiffuseLightColor+l_SpecularLighting;
	//return float4(l_TotalColor, 1.0);
    float4 l_color=tex2D(S0LinearSampler,IN.UV);
	
    return l_color*float4(l_TotalColor ,1);
    
}



technique tecOmniLight
{
    pass p0
    {        
        VertexShader =compile vs_3_0 RenderVS();
        PixelShader = compile ps_3_0 RenderPS();
    }
}
